import React, { useState, useRef } from 'react';
import styled from 'styled-components';
import { motion } from 'framer-motion';
import { colors, spacing, typography } from '../styles/variables';
import { Card, Title, Paragraph, Button, Flex, Grid } from '../styles/components';

const MindHeader = styled.div`
  text-align: center;
  padding: ${spacing.xl} 0;
  margin-bottom: ${spacing.xl};
`;

const RelaxationSection = styled(Card)`
  text-align: center;
  padding: ${spacing.xxl} ${spacing.lg};
  margin: ${spacing.xxl} 0;
`;

const BreathingCircle = styled(motion.div)`
  width: 200px;
  height: 200px;
  border-radius: 50%;
  background: ${props => {
    // 根据呼吸阶段设置不同的颜色
    switch(props.phase) {
      case '吸气':
        return 'linear-gradient(145deg, #a5f3fc, #06b6d4)'; // 柔和的青色
      case '屏息':
        return 'linear-gradient(145deg, #bfdbfe, #3b82f6)'; // 柔和的蓝色
      case '呼气':
        return 'linear-gradient(145deg, #c7d2fe, #6366f1)'; // 柔和的靛蓝色
      default:
        return 'linear-gradient(145deg, #0ea5e9, #0284c7)'; // 默认蓝色
    }
  }};
  margin: ${spacing.xxl} auto;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: white;
  cursor: pointer;
  text-align: center;
  
  // 添加3D视觉效果
  box-shadow: ${props => {
    // 根据呼吸阶段设置不同的阴影效果
    switch(props.phase) {
      case '吸气':
        return '0 10px 25px rgba(6, 182, 212, 0.4), inset 0 -8px 15px rgba(0, 0, 0, 0.2), inset 0 8px 10px rgba(255, 255, 255, 0.2)';
      case '屏息':
        return '0 10px 25px rgba(59, 130, 246, 0.4), inset 0 -8px 15px rgba(0, 0, 0, 0.2), inset 0 8px 10px rgba(255, 255, 255, 0.2)';
      case '呼气':
        return '0 10px 25px rgba(99, 102, 241, 0.4), inset 0 -8px 15px rgba(0, 0, 0, 0.2), inset 0 8px 10px rgba(255, 255, 255, 0.2)';
      default:
        return '0 10px 25px rgba(14, 165, 233, 0.4), inset 0 -8px 15px rgba(0, 0, 0, 0.2), inset 0 8px 10px rgba(255, 255, 255, 0.2)';
    }
  }};
  transform: ${props => props.active ? 'scale(1.05)' : 'scale(1)'};
  transition: all 0.3s ease;
`;

const BreathingPhase = styled.div`
  font-size: ${typography.fontSize.lg}; // 从sm(14px)增大到lg(18px)
  margin-bottom: 5px;
  height: 20px;
  // 根据呼吸阶段设置柔和的颜色
  color: ${props => {
    switch(props.phase) {
      case '吸气':
        return '#0891b2'; // 柔和的青色
      case '屏息':
        return '#1d4ed8'; // 柔和的蓝色
      case '呼气':
        return '#4338ca'; // 柔和的靛蓝色
      default:
        return '#0369a1'; // 默认深蓝色
    }
  }};
  font-weight: ${typography.fontWeight.medium};
`;

const BreathingCount = styled.div`
  font-size: 3rem;
  font-weight: ${typography.fontWeight.bold};
  // 使用浅色，与圆盘背景形成明显对比
  color: ${props => {
    switch(props.phase) {
      case '吸气':
        return '#e0f2fe'; // 浅青色
      case '屏息':
        return '#dbeafe'; // 浅蓝色
      case '呼气':
        return '#e0e7ff'; // 浅靛蓝色
      default:
        return '#ffffff'; // 纯白色
    }
  }};
  text-shadow: 1px 1px 3px rgba(0, 0, 0, 0.4); // 添加更明显的阴影以增强可读性
`;

const MeditationTimer = styled.div`
  font-size: ${typography.fontSize['3xl']};
  font-weight: ${typography.fontWeight.bold};
  color: ${colors.textPrimary};
  margin: ${spacing.lg} 0;
`;

const AffirmationCard = styled(Card)`
  background: linear-gradient(135deg, ${colors.backgroundSecondary} 0%, ${colors.background} 100%);
  text-align: center;
`;

const AffirmationText = styled.p`
  font-size: ${typography.fontSize.xl};
  font-style: italic;
  color: ${colors.textPrimary};
  margin: ${spacing.lg} 0;
`;

const JournalEntry = styled.textarea`
  width: 100%;
  min-height: 200px;
  background: ${colors.backgroundSecondary};
  border: 1px solid ${colors.border};
  border-radius: ${spacing.md};
  padding: ${spacing.lg};
  color: ${colors.textPrimary};
  font-size: ${typography.fontSize.base};
  font-family: ${typography.fontFamily};
  resize: vertical;

  &:focus {
    outline: none;
    border-color: ${colors.primary};
    box-shadow: 0 0 0 3px rgba(245, 158, 11, 0.2);
  }
`;

const activities = [
  { 
    id: 'breathing', 
    title: '呼吸练习', 
    description: '4-7-8呼吸法放松身心',
    icon: '💨'
  },
  { 
    id: 'meditation', 
    title: '冥想引导', 
    description: '10分钟正念冥想',
    icon: '🧘'
  },
  { 
    id: 'affirmations', 
    title: '积极肯定', 
    description: '每日正能量语句',
    icon: '✨'
  },
  { 
    id: 'journal', 
    title: '心灵日记', 
    description: '记录内心感受',
    icon: '📝'
  },
  { 
    id: 'music', 
    title: '放松音乐', 
    description: '自然音效助眠',
    icon: '🎵'
  },
  { 
    id: 'tips', 
    title: '减压贴士', 
    description: '实用心理调节方法',
    icon: '💡'
  }
];

const affirmations = [
  "我值得被爱和尊重",
  "我拥有克服困难的力量",
  "每一天我都变得更加自信",
  "我选择快乐和平静",
  "我接受生活中的变化",
  "我有能力实现我的目标",
  "我原谅自己和他人",
  "我活在当下，珍惜每一刻"
];

function MindStation() {
  const [breathingActive, setBreathingActive] = useState(false);
  const [breathingPhase, setBreathingPhase] = useState('准备开始');
  const [breathingCount, setBreathingCount] = useState(0);
  const [meditationTime, setMeditationTime] = useState(0);
  const [meditationActive, setMeditationActive] = useState(false);
  const [currentAffirmation, setCurrentAffirmation] = useState(0);
  const [journalEntry, setJournalEntry] = useState('');
  
  // 创建音频播放函数
  const playCountdownSound = () => {
    try {
      // 创建一个简单的音调作为倒计时音效
      const audioContext = new (window.AudioContext || window.webkitAudioContext)();
      const oscillator = audioContext.createOscillator();
      const gainNode = audioContext.createGain();
      
      oscillator.connect(gainNode);
      gainNode.connect(audioContext.destination);
      
      // 设置音调频率和类型
      oscillator.type = 'sine';
      oscillator.frequency.value = 880; // A5音符
      
      // 设置音量渐弱效果
      gainNode.gain.setValueAtTime(0.3, audioContext.currentTime);
      gainNode.gain.exponentialRampToValueAtTime(0.01, audioContext.currentTime + 0.5);
      
      // 播放并停止
      oscillator.start();
      oscillator.stop(audioContext.currentTime + 0.5);
    } catch (error) {
      console.log('音频播放失败:', error);
    }
  };
  
  // 创建语音提示函数
  const speakPhase = (phase) => {
    try {
      // 检查浏览器是否支持语音合成
      if ('speechSynthesis' in window) {
        // 创建语音合成实例
        const utterance = new SpeechSynthesisUtterance(phase);
        
        // 设置语音参数
        utterance.lang = 'zh-CN'; // 设置为中文
        utterance.rate = 0.8; // 语速稍慢
        utterance.pitch = 1; // 音调正常
        utterance.volume = 0.7; // 音量适中
        
        // 播放语音
        window.speechSynthesis.speak(utterance);
      }
    } catch (error) {
      console.log('语音播放失败:', error);
    }
  };

  const startBreathing = () => {
    setBreathingActive(true);
    setBreathingPhase('吸气...');
    setBreathingCount(4);
    
    // 播放吸气阶段语音提示
    speakPhase('吸气');
    
    // 吸气倒计时 (4秒)
    let inhaleCount = 4;
    const inhaleTimer = setInterval(() => {
      inhaleCount--;
      if (inhaleCount >= 0) {
        setBreathingCount(inhaleCount);
        // 播放倒计时音效
        if (inhaleCount > 0) {
          playCountdownSound();
        }
      }
      if (inhaleCount < 0) {
        clearInterval(inhaleTimer);
        // 屏息阶段
        setBreathingPhase('屏息...');
        setBreathingCount(7);
        
        // 播放屏息阶段语音提示
        speakPhase('屏息');
        
        // 屏息倒计时 (7秒)
        let holdCount = 7;
        const holdTimer = setInterval(() => {
          holdCount--;
          if (holdCount >= 0) {
            setBreathingCount(holdCount);
            // 播放倒计时音效
            if (holdCount > 0) {
              playCountdownSound();
            }
          }
          if (holdCount < 0) {
            clearInterval(holdTimer);
            // 呼气阶段
            setBreathingPhase('呼气...');
            setBreathingCount(8);
            
            // 播放呼气阶段语音提示
            speakPhase('呼气');
            
            // 呼气倒计时 (8秒)
            let exhaleCount = 8;
            const exhaleTimer = setInterval(() => {
              exhaleCount--;
              if (exhaleCount >= 0) {
                setBreathingCount(exhaleCount);
                // 播放倒计时音效
                if (exhaleCount > 0) {
                  playCountdownSound();
                }
              }
              if (exhaleCount < 0) {
                clearInterval(exhaleTimer);
                // 结束
                setBreathingPhase('准备开始');
                setBreathingCount(0);
                setBreathingActive(false);
              }
            }, 1000);
          }
        }, 1000);
      }
    }, 1000);
  };

  const startMeditation = () => {
    setMeditationActive(true);
    setMeditationTime(600); // 10分钟
    
    const timer = setInterval(() => {
      setMeditationTime(prev => {
        if (prev <= 1) {
          clearInterval(timer);
          setMeditationActive(false);
          return 0;
        }
        return prev - 1;
      });
    }, 1000);
  };

  const formatTime = (seconds) => {
    const mins = Math.floor(seconds / 60);
    const secs = seconds % 60;
    return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
  };

  const nextAffirmation = () => {
    setCurrentAffirmation((prev) => 
      prev < affirmations.length - 1 ? prev + 1 : 0
    );
  };

  return (
    <>
      <MindHeader>
        <Title>心灵驿站</Title>
        <Paragraph center>在这里放松身心，寻找内心的平静</Paragraph>
      </MindHeader>

      <Grid columns={3} gap={spacing.lg} style={{ margin: `${spacing.xl} 0` }}>
        {activities.map((activity, index) => (
          <Card 
            key={activity.id}
            as={motion.div}
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.5, delay: index * 0.1 }}
          >
            <Flex direction="column" align="center" style={{ textAlign: 'center' }}>
              <div style={{ fontSize: '3rem', marginBottom: spacing.md }}>
                {activity.icon}
              </div>
              <Title size="sm">{activity.title}</Title>
              <Paragraph secondary>{activity.description}</Paragraph>
            </Flex>
          </Card>
        ))}
      </Grid>

      <RelaxationSection>
        <Title size="md">呼吸练习</Title>
        <Paragraph>4-7-8呼吸法：吸气4秒，屏息7秒，呼气8秒</Paragraph>
        
        <BreathingCircle
          onClick={startBreathing}
          phase={breathingPhase.replace('...', '')}
          active={breathingActive}
          animate={{
            scale: breathingActive ? [1, 1.05, 1] : 1,
          }}
          transition={{
            duration: breathingActive ? 4 : 0,
            repeat: breathingActive ? Infinity : 0,
            repeatType: "reverse"
          }}
        >
          {breathingActive ? (
            <>
              <BreathingPhase phase={breathingPhase.replace('...', '')}>
                {breathingPhase.replace('...', '')}
              </BreathingPhase>
              <BreathingCount phase={breathingPhase.replace('...', '')}>
                {breathingCount}
              </BreathingCount>
            </>
          ) : (
            '开始练习'
          )}
        </BreathingCircle>
        
        <Paragraph secondary>
          通过调节呼吸节奏来激活副交感神经系统，帮助身体放松
        </Paragraph>
      </RelaxationSection>

      <Grid columns={2} gap={spacing.lg} style={{ margin: `${spacing.xl} 0` }}>
        <Card>
          <Title size="md">冥想计时</Title>
          <MeditationTimer>
            {formatTime(meditationTime)}
          </MeditationTimer>
          <Flex justify="center">
            <Button 
              variant="primary" 
              onClick={startMeditation}
              disabled={meditationActive}
            >
              {meditationActive ? '冥想中...' : '开始冥想'}
            </Button>
          </Flex>
          <Paragraph secondary style={{ marginTop: spacing.lg }}>
            正念冥想有助于提高专注力，减少焦虑和压力
          </Paragraph>
        </Card>

        <AffirmationCard>
          <Title size="md">积极肯定</Title>
          <AffirmationText>
            &quot;{affirmations[currentAffirmation]}&quot;
          </AffirmationText>
          <Flex justify="center">
            <Button variant="outline" onClick={nextAffirmation}>
              下一个
            </Button>
          </Flex>
          <Paragraph secondary style={{ marginTop: spacing.lg }}>
            积极的自我对话可以重塑思维模式，增强自信心
          </Paragraph>
        </AffirmationCard>
      </Grid>

      <Card style={{ margin: `${spacing.xl} 0 ${spacing.xxl} 0` }}>
        <Title size="md">心灵日记</Title>
        <Paragraph>记录您的感受和想法，释放内心压力</Paragraph>
        <JournalEntry
          value={journalEntry}
          onChange={(e) => setJournalEntry(e.target.value)}
          placeholder="写下您此刻的感受、想法或任何想要表达的内容..."
        />
        <Flex justify="flex-end" style={{ marginTop: spacing.md }}>
          <Button variant="primary">保存日记</Button>
        </Flex>
      </Card>
    </>
  );
}

export default MindStation;